// lib/pages/chat_detail_page.dart
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:multi_shop/models/msg.dart';
import 'package:multi_shop/models/user.dart';
import 'package:multi_shop/utils/ws.dart';
import 'package:uuid/uuid.dart';

class ChatDetailPage extends StatefulWidget {
  final String threadId;
  final String shopName;
  final String shopAvatar;
  const ChatDetailPage({
    super.key,
    required this.threadId,
    required this.shopName,
    required this.shopAvatar,
  });

  @override
  State<ChatDetailPage> createState() => _ChatDetailPageState();
}

class _ChatDetailPageState extends State<ChatDetailPage> {
  UserInfo? userInfo;
  final List<MallChatMessage> _msgs = [
    MallChatMessage(
      id: 1,
      sessionId: 1,
      shopId: 1,
      userId: 9,
      senderRole: 'merchant',
      contentType: 'text',
      content: '您好～',
      receiveUid: 9,
      createdAt: DateTime.now().subtract(const Duration(minutes: 3)),
    ),
    MallChatMessage(
      id: 2,
      sessionId: 1,
      shopId: 1,
      userId: 9,
      senderRole: 'user',
      contentType: 'text',
      content: '在的，想了解下发货时间',
      receiveUid: 1,
      createdAt: DateTime.now().subtract(const Duration(minutes: 2)),
    ),
  ];
  final _input = TextEditingController();
  final _scroll = ScrollController();
  @override
  void initState() {
    super.initState();
    userInfo = GetStorage().read('userInfo');
  }

  @override
  void dispose() {
    _input.dispose();
    _scroll.dispose();
    super.dispose();
  }

  void _send() {
    final s = _input.text.trim();
    if (s.isEmpty) return;
    debugPrint(json.encode(userInfo));
    MallChatMessage msg = MallChatMessage(
      id: 3,
      sessionId: 1,
      shopId: 1,
      userId: userInfo!.id,
      senderRole: 'user',
      contentType: 'text',
      content: s,
      receiveUid: 1,
      createdAt: DateTime.now(),
    );
    setState(() {
      debugPrint(json.encode(msg));
      _msgs.add(msg);
    });
    _input.clear();
    Future.delayed(const Duration(milliseconds: 50), () {
      if (_scroll.hasClients) {
        _scroll.animateTo(
          _scroll.position.maxScrollExtent + 60,
          duration: const Duration(milliseconds: 200),
          curve: Curves.easeOut,
        );
      }
    });

    // TODO: 发送到后端 / WebSocket
    debugPrint('send: ${json.encode(msg)}');
    chatWs.sendText(msg);
  }

  // void _send() {
  //   final t = inputCtrl.text.trim();
  //   if (t.isEmpty) return;
  //   chatWs.sendText(t);
  //   // 本地先插一条我的气泡（如果服务端也会回显，可按 client_msg_id 去重）
  //   msgs.add(
  //     MallChatMessage.fromJson({
  //       'type': 'msg',
  //       'content_type': 'text',
  //       'content': t,
  //       "target_type": "merchant",
  //       "target_id": 1,
  //     }),
  //   );
  //   inputCtrl.clear();
  // }

  String _fmt(DateTime dt) {
    final h = dt.hour.toString().padLeft(2, '0');
    final m = dt.minute.toString().padLeft(2, '0');
    return '$h:$m';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0,
        title: Row(
          children: [
            ClipOval(
              child: Image.network(
                widget.shopAvatar,
                width: 32,
                height: 32,
                fit: BoxFit.cover,
                errorBuilder: (_, __, ___) => Container(
                  width: 32,
                  height: 32,
                  color: Colors.grey.withValues(alpha: 0.2),
                  child: const Icon(Icons.store, size: 18),
                ),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(widget.shopName, overflow: TextOverflow.ellipsis),
            ),
          ],
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              controller: _scroll,
              padding: const EdgeInsets.all(12),
              itemCount: _msgs.length,
              itemBuilder: (_, i) {
                final m = _msgs[i];
                final align = m.senderRole == 'user'
                    ? CrossAxisAlignment.end
                    : CrossAxisAlignment.start;
                final bubbleColor = m.senderRole == 'user'
                    ? Theme.of(
                        context,
                      ).colorScheme.primary.withValues(alpha: 0.12)
                    : Colors.grey.withValues(alpha: 0.12);

                return Column(
                  crossAxisAlignment: align,
                  children: [
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 6),
                      padding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 8,
                      ),
                      decoration: BoxDecoration(
                        color: bubbleColor,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(m.content),
                    ),
                    Text(
                      _fmt(m.createdAt!),
                      style: const TextStyle(fontSize: 11, color: Colors.grey),
                    ),
                  ],
                );
              },
            ),
          ),
          SafeArea(
            top: false,
            child: Container(
              padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  top: BorderSide(color: Colors.grey.withValues(alpha: 0.15)),
                ),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _input,
                      minLines: 1,
                      maxLines: 4,
                      decoration: InputDecoration(
                        hintText: '输入消息…',
                        isCollapsed: true,
                        contentPadding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 10,
                        ),
                        filled: true,
                        fillColor: Colors.grey.withValues(alpha: 0.06),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20),
                          borderSide: BorderSide.none,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  IconButton(
                    onPressed: _send,
                    icon: const Icon(Icons.send),
                    color: Theme.of(context).colorScheme.primary,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
